﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using dotNetMembership = System.Web.Security.Membership;
using dotNetRoles = System.Web.Security.Roles;
using Binding = System.Web.Mvc.BindingHelperExtensions;
using StarterKits.Mvc.Filters.FormsAuthentication;
using StarterKits.Mvc.Membership.Controllers;
using P.InOut.NetMvc.Logging;
using P.InOut.NetMvc.Models;
using P.InOut.NetMvc.Properties;

namespace P.InOut.NetMvc.Controllers
{
    public class ProfilesController : InOutController
    {
        private InOutDatabaseLogger logger = new InOutDatabaseLogger();

        public override ActionResult Index()
        {
            if (Request.Params["updated"] == "true")
                ViewData["SuccessMessage"] = "Updated";

            using (InOutDataContext db =
                new InOutDataContext(Settings.Default.dbConn))
            {
                MembershipUser user = dotNetMembership.GetUser();

                UserProfileData viewData = new UserProfileData()
                {
                    User = user,
                    Profile = db.Profiles.Single(p => p.UserId == (Guid)user.ProviderUserKey)
                };

                return View("Index", viewData);
            }
        }

        public override ActionResult Detail(object id)
        {
            return RedirectToAction("Index", "Profiles");
        }

        public override ActionResult Create()
        {
            return RedirectToAction("Index");
        }

        [NonAction]
        public virtual void OnBeforeUpdate(string userName) { }

        [NonAction]
        public virtual void OnAfterUpdate(string userName)
        {
            // Log User Added to Role
            string message = string.Format("User: {0} Updated Their Profile", userName);
            LogAction(message, BitFactory.Logging.LogSeverity.Info, User.Identity.Name);
        }

        [RequiresAuthentication()]
        public override ActionResult Update(object id)
        {
            using (InOutDataContext db =
                new InOutDataContext(Settings.Default.dbConn))
            {
                // Get username from hidden field
                string userName = Request.Form["UserName"];

                OnBeforeUpdate(userName);

                Profile profile = db.Profiles.Single<Profile>(p => Guid.Equals(p.UserId, id));

                // Update profile
                if (Request.Form.AllKeys.Contains<string>("inStatus"))
                {
                    bool inStatus = Request.Form["inStatus"] == "In" ? true : false;
                    bool officeStatus = Request.Form["officeStatus"] == "Office" ? true : false;
                    if (inStatus)
                    {
                        profile.InStatus = true;
                        if (officeStatus)
                            profile.OfficeStatus = true;
                        else
                            profile.OfficeStatus = false;
                    } else {
                        profile.InStatus = false;
                    }
                } else {
                    Binding.UpdateFrom(profile, Request.Form);
                }

                profile.DateTimeLastUpdated = DateTime.Now;

                // Submit update to DB
                db.SubmitChanges();

                OnBeforeUpdate(userName);

                string source = Request.Form["RequestFrom"];
                if (source == "Profiles")
                    return RedirectToAction("Index", "Profiles", new { updated = "true" });
                else
                    return RedirectToAction("Index", "Updates");
            }
        }

        public override ActionResult Delete(object id)
        {
            return RedirectToAction("Index");
        }

        private void LogAction(string message, BitFactory.Logging.LogSeverity severity, string userName)
        {
            // Execute the log entry
            logger.Execute("InOut", "Administration", message, System.DateTime.Now,
                severity, userName);
        }
    }
}
